<template>
	<div class="auditor">

    <table-set :tableHeader="tableHeader" @headerSet="headerSet"></table-set>

		<orderStatistics :myInfo ='myInfo' :roleID='roleID'/>

		<!-- 列表查找 -->
		<span class="down-execel">
			<!-- <Icon type="ios-funnel-outline" /><a href="javascript:;">筛选条件</a> -->
			<Poptip v-model="showFilter" placement="bottom-end"  @on-popper-show ='getAllAgent'>
				<!-- <Icon type="ios-funnel-outline" /> -->
				<i class="el-icon-search poptip-condition-add"></i>
				<a href="javascript:;">列表查找</a>
				<!-- <div slot="title"><i></i></div> -->
				<div slot="content">
					<Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
						<i class="el-icon-plus poptip-condition-add"></i>
						<a href="javascript:;" class='poptip-condition-add'>添加过滤条件</a>


						<div slot="content" class="condition-list">
							<ul>
								<li v-for="(item, index) in columns" :key="index" class='poptip-condition-item' @click="addFilterCondition(item)">{{item.label}}</li>
							</ul>
						</div>
					</Poptip>

					<el-form :model="conditionForm" @submit.native.prevent ref="conditionForm" label-width="120px" class="demo-dynamic">
						<el-form-item v-for="(condition, index) in conditionForm.condition" :label="condition.label" :key="condition.key"
							:prop="'condition.' + index + '.value'" :rules="{
									required: true, message: condition.label +'不能为空', trigger: 'blur'
								}">
							<el-date-picker
								v-model="submitTime"
								type="daterange"
								placeholder="选择日期"
								value-format="yyyy-MM-dd"
								@input = 'changInput'
								:validate-event='false'
								size="small"
								v-if='condition.label === "提交时间"'>
							</el-date-picker>

							<el-select v-else-if='condition.label === "专利类型"' v-model="condition.value" placeholder="请选择专利类型" size="small">
								<el-option label="发明专利" value="发明专利"></el-option>
								<el-option label="实用新型" value="实用新型"></el-option>
								<el-option label="外观设计" value="外观设计"></el-option>
								<el-option label="不确定" value="不确定"></el-option>
							</el-select>
							<el-select
								size="small"
								filterable
								v-model="condition.value"
								v-else-if='condition.label === "代理人"'>
								<el-option
									v-for="item in agentOptions"
									:key="item.id"
									:label="item | agentNumAddName"
									:value="item.id">
								</el-option>
							</el-select>

							<el-input v-else size="small" v-model="condition.value" @keyup.enter.native="submitsearch('conditionForm')"></el-input>
							<el-button @click.stop="removeDomain(condition)" size="mini" v-no-more-click:3000>删除</el-button>
						</el-form-item>
						<div class='btns'>
							<el-button @click="submitsearch('conditionForm')" size="mini" v-no-more-click:3000>查询</el-button>
							<el-button @click.stop="resetForm('conditionForm')" size="mini" v-no-more-click:3000>重置</el-button>
						</div>

					</el-form>
				</div>
			</Poptip>
		</span>

		<el-table
			v-if="table_show"
			:data="tableData"
			@row-click="lookOrder"
			border
			style="width: 100%"
			ref="orderTb"
			height="87%"
			@sort-change='tableSortChange'
			v-loading="loading">
			<el-table-column prop="id" label="ID" min-width="60" align="left">
				<template slot-scope="scope">{{(scope.$index+1)+(currentPage-1)*tableSize}}</template>
			</el-table-column>
			<template v-for="(item, index) in tableHeader">

				<el-table-column :key="index" v-if="item.label == '等待审核时间' && item.is_show" show-overflow-tooltip label="等待审核时间(天)" min-width="160" prop="two_pivot_created_at" align="left" sortable='custom'>
					<template slot-scope="scope">
						<span :class="{'unfinish': getAuditorDate(scope.row) > 3}">
							{{ getAuditorDate(scope.row) }}
						</span>
					</template>
				</el-table-column>
				<el-table-column :key="index" v-if="item.label == '订单编号' && item.is_show" show-overflow-tooltip prop="order_number" label="订单编号" min-width="200" align="left" sortable='custom'></el-table-column>
				<el-table-column :key="index" v-if="item.label == '专利类型' && item.is_show" show-overflow-tooltip prop="type" label="专利类型" min-width="120" align="left" sortable='custom'></el-table-column>
				<el-table-column :key="index" v-if="item.label == '流程状态' && item.is_show" show-overflow-tooltip prop="status" label="流程状态" min-width="120" align="left" sortable='custom'></el-table-column>
				<el-table-column :key="index" v-if="item.label == '拟申报专利名称' && item.is_show" show-overflow-tooltip prop="patent_name" label="拟申报专利名称" min-width="150" align="left" sortable='custom'></el-table-column>
				<el-table-column :key="index" v-if="item.label == '代理人' && item.is_show" show-overflow-tooltip prop="agent.name" label="代理人" min-width="120" align="left" sortable></el-table-column>
				<el-table-column :key="index" v-if="item.label == '审核次数' && item.is_show" show-overflow-tooltip prop="opinions_count" label="审核次数" min-width="110" align="left" sortable='custom'></el-table-column>
				<el-table-column :key="index" v-if="item.label == '内容审核文件' && item.is_show" prop="review_file" label="内容审核文件" min-width="200" align="left">
					<template slot-scope="scope">
						<div @click.stop class='flie-hid'>
							<a v-for="item in scope.row.reviewfileArr" :key="item.id" :href="baseUrl + '/api/download?path=' + item.path"
							:download="item.path" :title="item.path.split('/')[2]" :class="['el-icon-tickets file_sh', {'free-file': item.path.indexOf('免审') > -1}]"></a>
							<!-- {{ scope.row.reviewfileArr}} -->
						</div>
					</template>
				</el-table-column>
				<el-table-column :key="index" v-if="item.label == '修改时间' && item.is_show" show-overflow-tooltip prop="updated_at" label="修改时间" min-width="180" align="left" sortable='custom'></el-table-column>
			</template>
			<el-table-column width="100" align="center" label="操作" fixed="right" v-if="checked99">
				<template slot-scope="scope">
					<el-button :disabled="scope.row.status=='案件修改中'" type="primary" size="small" @click.stop="auditorOrder(scope.row)" v-no-more-click:3000>审核</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
			:page-sizes="pageSizes" :page-size="Number(pageSize)" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>

		<auditorDialog ref="auditorDialog"  @refresh="refreshData"/>
		<lookDialog :formProcess="false" :order_process="order_process" :order_agent="order_agent" ref="orderDialog"></lookDialog>
	</div>
</template>
<script>
	import {
		getOrderList,
		getOrder,
		delOrder
	} from "~/api/order";
	import {
		doAuditor
	} from "~/api/auditor";
	import {
		getOrderAuditorList
	} from "~/api/order";

	import orderFn from "../order/getOrderList"
	// 表头统计
	import orderStatistics from "~/components/orderStatistics"
	// 扣款
	import tableSet from '~/components/tableSet'
	import lookDialog from '../order/dialogPage/dialogOrder'
	import { getMyInfo } from "~/api/user";

	import auditorDialog from './components/auditor'
	export default {
		components: {
			orderStatistics,
			auditorDialog,
			tableSet,
			lookDialog
		},
		data() {
			return {
				order_process: {},
				order_agent: {},
				table_show: true,
				tableHeader: [
					{
						label: '等待审核时间',
						prop: 'two_pivot_created_at',
						is_show: true
					},
					{
						label: '订单编号',
						prop: 'order_number',
						is_show: true
					},
					{
						label: '专利类型',
						prop: 'type',
						is_show: true
					},
					{
						label: '流程状态',
						prop: 'status',
						is_show: true
					},
					{
						label: '拟申报专利名称',
						prop: 'patent_name',
						is_show: true
					},
					{
						label: '代理人',
						prop: 'agent.name',
						is_show: true
					},
					{
						label: '审核次数',
						prop: 'opinions_count',
						is_show: true
					},
					{
						label: '内容审核文件',
						prop: 'review_file',
						is_show: true
					},
					{
						label: '修改时间',
						prop: 'updated_at',
						is_show: true
					}
				],
				tableSize: 10, //一页几条
				tableStart: 0, //table数组过滤的第一条索引
				tableEnd: 10, //table数组过滤的最后一条索引
				currentPage: 1, //目前在第几页
				pageSizes: [25, 50], //一页可以几条
				loading: false,
				tableData: [],
				isFixed: "right",
				//默认域名
				baseUrl: global.baseurl,
				order: "",
				total: 0,
				showFilter: false, // 控制显示筛选条件
				showFilterCondition: false,
				conditionForm: {
					condition: []
				}, //筛选条件
				columns: [
					{
						label: '订单编号',
						id: 1,
						parameter: 'order_number'
					},
					{
						label: '专利类型',
						id: 2,
						parameter: 'type'
					},
					{
						label: '专利名称',
						id: 3,
						parameter: 'patent_name'
					},
					{
						label: '提交时间',
						id: 10,
						parameter: 'subimt_time'
					},
					{
						label: '代理人',
						id: 3,
						parameter: 'agent_id'
					},
				],
				searchValue: '',
				submitTime: [],
				agentOptions: [],
				paramsByOrder: {
					sort_str: 'two_pivot_created_at',
					sort_order: 'asc'
				},
				myInfo: {},
				roleID: '',
				checked99: true
			};
		},
		async asyncData({
			$axios,
			store
		}) {
			let params = {
				sort_str: 'two_pivot_created_at',
				sort_order: 'asc'
			}
			return orderFn.getOrderAuditor($axios, store, params)

		},
		created () {
			// this.myInfo.waitAuditor = this.total
			// this.roleID = this.$store.state.user.id
		},
		methods: {
			async getMyinfo () {
				let myInfo = await getMyInfo(this.$axios);
				if (myInfo.data.status == 'success') {
					this.$store.commit("setRoleInfo",myInfo.data.data)
					this.$store.commit("setUser",myInfo.data.data);
				}
			},
			lookOrder(row) {
				if (window.getSelection().toString() === '') {
					this.order_process = row.process;
					this.order_agent = row.agent || {};
					this.$refs.orderDialog.showDialog(row.id, "处理中");
				}
			},
			refreshData() {
				this.getMyinfo()
				this.changeData()
			},
			// agentAnwser(data) {
			// 	this.$refs['agent-anwser'].showOn(data, 'auditor')
			// },
			headerSet(data) {
				this.table_show = false
				this.tableHeader = data
				this.$nextTick(() => {
					this.table_show = true
				})
				if(data.every(v => v.is_show == false)) {
					this.checked99 = false
				}
				if (data.some(v => v.is_show == true)) {
					this.checked99 = true
				}
			},

			// deduction (data, formName) {
			// 	this.$refs[formName].validate(valid => {
			// 		if (valid) {
			// 			this.$refs['deductionDialog'].show(data, this.form.review)
			// 		}
			// 	})
			// },

			auditorOrder(val) {
				this.$refs['auditorDialog'].show(val)
			},

			// 刷新数据
			changeData() {
				let params = Object.assign({}, this.paramsByOrder)
				params.status = '案件内审中'
				params.auditor_id = this.$store.state.user.id
				getOrderAuditorList(this.$axios, params)
				.then(res=>{
					if(res.data.code==200){
						this.loading = false
						this.tableData = res.data.data;
						this.pageSize = res.data.page.per_page;
						this.tableSize = res.data.page.per_page;
						this.tableEnd = res.data.page.per_page;
						this.total = res.data.page.total;
						for (let i = 0; i < this.tableData.length; i++) {
							this.splitFiles(this.tableData[i])
						}
					}
				})
			},

			//选择一页几条
		 	async	handleSizeChange(size) {
				this.paramsByOrder.perPage = size
				this.paramsByOrder.page = 1
				let params = Object.assign({}, this.paramsByOrder)
				params.status = '案件内审中'
				params.auditor_id = this.$store.state.user.id

				await getOrderAuditorList(this.$axios, params)
				.then(res=>{
					if(res.data.code== 200){
						this.tableData = res.data.data
						for (let i = 0; i < this.tableData.length; i++) {
							this.splitFiles(this.tableData[i])
						}
					}
				})

			},
			//选择第几页
			handleCurrentChange(val) {
				let params = Object.assign({}, this.paramsByOrder)
				params.status = '案件内审中'
    		params.auditor_id = this.$store.state.user.id
				params.page = val
				getOrderAuditorList(this.$axios, params)
				.then(res=>{
					if(res.data.code==200){
						this.tableData = res.data.data
						for (let i = 0; i < this.tableData.length; i++) {
							this.splitFiles(this.tableData[i])
						}
					}
				})
			},
			getAllAgent() {
				this.$axios.get('api/user/agent/all')
					.then(res => {
						if (res.data.code == 200) {
							this.agentOptions = res.data.data
						}
					})
					.catch(err => {
						this.$message({
							type: "err",
							message: err
						});
					});

			},

			// readAuditor(data, index) {
			// 	let ids = []
			// 	data.forEach(v => {
			// 		ids.push(v.id)
			// 	});
			// 	this.$axios.put('/api/opinion/update_read_status', {
			// 		ids: ids
			// 	}).then(res => {
			// 		if (res.data.code == 200) {
			// 			this.tableData[index].noRead = 0
			// 		} else {
			// 			this.$message({
			// 				type: 'error',
			// 				message: res.data.message
			// 			})
			// 		}
			// 	})
			// },
			// showAuditRecord() {
			// 	this.form = {}
			// },

			getAuditorDate(itemData) {
				if (!itemData.two_pivot_created_at) {
					return '暂无耗时'
				}
				let createDay = itemData.two_pivot_created_at;
				//获取接单的时间戳
				createDay = createDay.replace(/-/g, "/");
				var createTime = new Date(createDay).getTime();
				//获取当前的时间戳
				var nowTime = new Date().getTime();
				//获取处理时间戳
				let cha = nowTime - createTime;
				//转换天数

				let round2 = (cha / 1000 / 60 / 60 / 24).toFixed(2)
			 	let	processingTime = (Math.ceil(round2 * 10) / 10).toFixed(1)
				if (processingTime < 0) {
					return '0.0'
				}  else if (processingTime < 0.1) {
					return '0.1'
				} else {
					return processingTime;
				}
			},
			search() {
				this.currentPage = 1
				for (var i = 0; i < this.conditionForm.condition.length; i++) {
					let a = this.conditionForm.condition[i].parameter
					if (this.conditionForm.condition[i].parameter === 'subimt_time') {
						this.paramsByOrder.start_time = this.submitTime[0]
						this.paramsByOrder.end_time = this.submitTime[1]
					}
					this.paramsByOrder[a] = this.conditionForm.condition[i].value
				}

				// 处理分页数据
				delete this.paramsByOrder.page

				// 处理排序状态
				delete this.paramsByOrder.sort_str
				delete this.paramsByOrder.sort_order
				this.$refs['orderTb'].clearSort()

				this.loading = true
				let params = Object.assign({}, this.paramsByOrder)
				params.status = '案件内审中'
    		params.auditor_id = this.$store.state.user.id
				getOrderAuditorList(this.$axios, params)
				.then(res=>{
					if(res.data.code==200){
						this.loading = false
						this.tableData = res.data.data;
						this.pageSize = res.data.page.per_page;
						this.tableSize = res.data.page.per_page;
						this.tableEnd = res.data.page.per_page;
						this.total = res.data.page.total;
						for (let i = 0; i < this.tableData.length; i++) {
							this.splitFiles(this.tableData[i])
						}
					}
				})
			},
			// 添加条件筛选
			addFilterCondition(item) {
				let filterItem = {
					value: '',
					label: item.label,
					parameter: item.parameter,
					key: Date.now()
				}

				if (this.conditionForm.condition.length > 0) {
					let conditionlabels = []
					for (let i = 0; i < this.conditionForm.condition.length; i++) {
						conditionlabels.push(this.conditionForm.condition[i].label)
					}
					let Check = conditionlabels.indexOf(item.label)
					Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
				} else {
					this.conditionForm.condition.push(filterItem)
				}

				this.showFilterCondition = false;
			},
			resetForm(formName) {
				this.$refs[formName].resetFields()
				this.$refs['orderTb'].clearSort()
				this.conditionForm.condition.forEach(v => {
					if (v.value) {
						v.value = null
					}
				});
				this.submitTime = []
				this.paramsByOrder = {
				}
				let params = Object.assign({}, this.paramsByOrder)
				params.status = '案件内审中'
    			params.auditor_id = this.$store.state.user.id
				// getOrderAuditorList(this.$axios, params)
				// .then(res=>{
				// 	if(res.data.code==200){
				// 		this.loading = false
				// 		this.tableData = res.data.data;
				// 		this.pageSize = res.data.page.per_page;
				// 		this.tableSize = res.data.page.per_page;
				// 		this.tableEnd = res.data.page.per_page;
				// 		this.total = res.data.page.total;
				// 		for (let i = 0; i < this.tableData.length; i++) {
				// 			this.splitFiles(this.tableData[i])
				// 		}
				// 	}
				// })
				// this.showFilter = false
				// this.showFilterCondition = false
			},
			submitsearch(formName) {
					let that = this
					this.$refs[formName].validate((valid, prop) => {
						let props = []
						for (let k in prop) {
							props.push(prop[k][0].field)
							if (prop[k][0].message = '提交时间不能为空') {
								if (that.submitTime) {
									if(	that.submitTime.length > 0	) {
										that.$refs[formName].clearValidate([prop[k][0].field])
										let timeIndex = props.indexOf('提交时间不能为空')
										props.splice(timeIndex, 1)
									}
								} else {
									return false
								}
							}
						}
						if (props.length) {
							that.$refs[formName].validateField(props, (valid2) => {
								if(valid2) {
									return false;
								} else {
                  that.search()
				this.showFilter = false
								}
							})
						} else {
				this.showFilter = false
							that.search()
						}
					})
      },
      removeDomain(item) {
				this.showFilter = true
				delete this.paramsByOrder[item.parameter]
        let index = this.conditionForm.condition.indexOf(item)
        if (index !== -1) {
          this.conditionForm.condition.splice(index, 1)
				}
				if (item.label === '提交时间') {
					this.submitTime = []
					delete this.paramsByOrder.start_time
					delete this.paramsByOrder.end_time
				}
				this.search()
			},
			changInput () {
				this.$refs['conditionForm'].clearValidate();
			},
			// 表格排序
			tableSortChange(column) {
				// if (column.order === 'descending') {
				// 	this.paramsByOrder.sort_str = column.prop
				// 	this.paramsByOrder.sort_order = 'desc'
				// } else {
				// 	this.paramsByOrder.sort_str = column.prop
				// 	this.paramsByOrder.sort_order = 'asc'
				// }
				if (column.order == 'ascending') {
					this.paramsByOrder.sort_str = column.prop
					this.paramsByOrder.sort_order = 'asc'
				} else if (column.order == 'descending') {
					this.paramsByOrder.sort_str = column.prop
					this.paramsByOrder.sort_order = 'desc'
				} else {
					delete this.paramsByOrder.sort_str
					delete this.paramsByOrder.sort_order
				}
				if (column.prop == 'agent.name') {
					return
				}
				this.loading = true
				let params = Object.assign({}, this.paramsByOrder)
				params.status = '案件内审中'
    		params.auditor_id = this.$store.state.user.id
				getOrderAuditorList(this.$axios, params)
				.then(res=>{
					if(res.data.code==200){
						this.loading = false
						this.tableData = res.data.data;
						this.pageSize = res.data.page.per_page;
						this.tableSize = res.data.page.per_page;
						this.tableEnd = res.data.page.per_page;
						this.total = res.data.page.total;
						for (let i = 0; i < this.tableData.length; i++) {
							this.splitFiles(this.tableData[i])
						}
					}
				})
			},
			splitFiles (pData) {
				if (
						pData.review_file == null ||
						pData.review_file == ""
				) {} else {
						pData.reviewfileArr = [];
						let reviewfile = pData.review_file.split("&");
						for (var j in reviewfile) {
								let itemobj = {
										id: j + 1,
										path: reviewfile[j],
										file: ''
								};
								pData.reviewfileArr.push(itemobj);
						}
				}

				//已完成文件 切分组件
				if (
						pData.fish_file == null ||
						pData.fish_file == ""
				) {} else {
						pData.fishfileArr = [];
						let fishfile_Arr = pData.fish_file.split("&");
						for (var f in fishfile_Arr) {
								let itemobj = {
										id: f + 1,
										path: fishfile_Arr[f],
										file: ''
								};
								let itemArr = itemobj.path.split("/")
								itemobj.path = itemArr[itemArr.length - 1]
								itemobj.file = itemArr.slice(0, 2).join("/");
								pData.fishfileArr.push(itemobj);
						}
				}
			}
		},
		filters: {
			// getAuditorDate: function (value) {
			//   console.log(value)

			// }
		}
	};
</script>
<style lang="less" scoped>
	.auditor {
		height: 100%; //撑满表格
		#IMTable {
			height: 70%; //撑满表格
		}
	}


	.file_sh {
		font-size: 25px;
		margin-right: 10px;
	}
	.free-file {
		position: relative;
		&::after {
			content: '';
			width: 5px;
			height: 5px;
			display: block;
			border-radius: 50%;
			background-color: red;
			position: absolute;
			right: 2px;
			top: 0;
		}
	}
	.lookAuditRecord {

		ul {
			list-style: none;
			padding: 0 0 30px 0;

			li {
				// height: 30px;
				line-height: 30px;
			}

			.AuditDetails {
				margin-left: 30px;
			}
		}
	}

	.tableLastCol1 {
		padding-left: 50px;
	}
	.down-execel {
		display: inline-block;
		height: 40px;
		line-height: 40px;
		color: #333333;
		font-size: 14px;
		// float: right;
		margin-right: 20px;
	}
	.el-main .ivu-poptip .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 480px;
		// height: 300px;
		overflow-y: scroll;
	}

	.poptip-condition {
		display: block;
		margin-top: 10px;

		.poptip-condition-item {
			line-height: 25px;
			cursor: pointer;
		}

		.poptip-condition-add {
			font-size: 14px;
		}
	}

	.demo-dynamic {
		padding-left: 10px;

		.el-form-item {
			margin-bottom: 12px;
		}

		.el-input {
			width: 240px;
		}

		.el-date-editor {
			width: 240px;
		}

		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}

		.el-form-item__error {
			padding-top: 0;
		}

	}

	.el-main .poptip-condition .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 180px;
	}
	.flex-line {
		display: flex;
		.title {
				text-align: justify;
				text-align-last: justify;
				flex: 0 0 80px;
		}
  .content {
		flex: 1;
		.time {
			float: right;
			margin-left: 20px;
			color: #909399;
			font-weight: normal;
			font-size: 14px;
		}
  }
  }
	.dialog-title {
		&-text {
			font-size: 20px;
			// font-weight: 700;
			margin-right: 80px;
		}
		&-hint{
			font-size: 16px;
			margin-right: 10px;
		}
		&-hint:nth-last-chil(1) {
			margin-right: 0;
		}
	}
	.free-drop-menu {
		.el-dropdown-menu__item {
			padding: 0 10px;
			line-height: 0;
			.normal-btn {
				width: 90px;
				height: 26px;
				padding: 0;
				span {
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
		}
	}
</style>
